package com.tanhua.server.service;


import com.alibaba.dubbo.config.annotation.Reference;
import com.tanhua.commons.aliyun.utils.AliyunOssUtils;
import com.tanhua.commons.utils.FileUtils;
import com.tanhua.domain.db.User;
import com.tanhua.domain.db.UserInfo;
import com.tanhua.domain.mongo.*;
import com.tanhua.domain.vo.Comments;
import com.tanhua.domain.vo.Movements;
import com.tanhua.domain.vo.PageResult;
import com.tanhua.domain.vo.VisitorsVo;
import com.tanhua.dubbo.server.api.UserInfoApi;
import com.tanhua.dubbo.server.api.mongo.CommentApi;
import com.tanhua.dubbo.server.api.mongo.PublishApi;
import com.tanhua.dubbo.server.api.mongo.VisitorsApi;
import com.tanhua.server.interceptor.UserThreadLocal;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.*;

@Service
public class MovementsService {

    @org.apache.dubbo.config.annotation.Reference
    private PublishApi publishApi;

    @Reference
    private CommentApi commentApi;

    @Reference
    private UserInfoApi userInfoApi;

    @Reference
    private VisitorsApi visitorsApi;

    @Autowired
    private AliyunOssUtils ossUtils;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 发布动态
     */
    public void saveMovements(Publish publish,
                                MultipartFile[] multipartFile) throws IOException {
        //图片上传
        List<String> imageUrls = new ArrayList<>();

        for (MultipartFile file : multipartFile) {
            String filePath = FileUtils.getFilePath(file.getOriginalFilename());
            String imageUrl = ossUtils.upload(filePath, file.getInputStream());
            imageUrls.add(imageUrl);
        }
        //保存动态信息
        publish.setMedias(imageUrls);
        publishApi.save(publish);
    }


    public ResponseEntity queryAlbumList(Long userId, Integer page, Integer pageSize) {
        PageResult pageResult = publishApi.findAll(page, pageSize, userId,0);
        return ResponseEntity.ok(pageResult);
    }

    public ResponseEntity queryUserPublishList(Integer page, Integer pageSize) {
        PageResult pageResult = publishApi.findAll(page, pageSize, UserThreadLocal.getUserId(),1);
        return ResponseEntity.ok(pageResult);
    }

    public ResponseEntity queryRecommendPublishList(Integer page, Integer pageSize) {
        PageResult pageResult = publishApi.findAll(page, pageSize, UserThreadLocal.getUserId(),2);
        return ResponseEntity.ok(pageResult);
    }

    public ResponseEntity queryMovementsById(String publishId) {
        Movements movements = publishApi.findById(publishId);
        return ResponseEntity.ok(movements);
    }

    /**
     * 点赞，喜欢，评论
     *    commentType; //评论类型，1-点赞，2-评论，3-喜欢
     *    pubType; //评论内容类型： 1-对动态操作 2-对视频操作 3-对评论评论
     */
    public ResponseEntity saveComment(Comment comment) {
        return ResponseEntity.ok(commentApi.save(comment));
    }

    /**
     * 取消点赞，喜欢
     *   commentType; //评论类型，1-点赞，2-评论，3-喜欢
     *   pubType; //评论内容类型： 1-对动态操作 2-对视频操作 3-对评论评论
     */
    public ResponseEntity removeComment(Comment comment) {
        return ResponseEntity.ok(commentApi.remove(comment));
    }


    public ResponseEntity queryCommentsList(String publishId, Integer page, Integer pageSize) {

        PageResult result = commentApi.findAll(publishId, page, pageSize);

        List<Comment> commentList = (List<Comment>) result.getItems();

        List<Comments> commentsList = new ArrayList<>();

        for (Comment comment : commentList) {
            Comments comments = new Comments();
            BeanUtils.copyProperties(comment, comments);
            comments.setId(comment.getId().toString());
            comments.setCreateDate(new DateTime(comment.getCreated()).toString("yyyy年MM月dd日 HH:mm"));
            UserInfo info = userInfoApi.findByUserId(comment.getUserId());
            BeanUtils.copyProperties(info, comments);
            comments.setHasLiked(0); //是否点赞
            commentsList.add(comments);
        }

        result.setItems(commentsList);
        return ResponseEntity.ok(result);
    }


    public ResponseEntity queryVisitorsList() {

        User user = UserThreadLocal.get();

        String redisKey = "visitors_" + user.getId();

        String data = this.redisTemplate.opsForValue().get(redisKey);

        List<Visitors> visitors = null;

        if (StringUtils.isEmpty(data)) {
            //按照数量查询
            visitors = this.visitorsApi.topVisitor(user.getId(), 6);
        } else {
            //按照时间查询
            visitors = this.visitorsApi.topVisitor(user.getId(), Long.valueOf(data));
        }

        List<VisitorsVo> result = new ArrayList<>();

        for (Visitors visitor : visitors) {
            UserInfo info = userInfoApi.findByUserId(visitor.getVisitorUserId());
            VisitorsVo visitorsVo = new VisitorsVo();
            BeanUtils.copyProperties(info,visitorsVo);
            visitorsVo.setTags(StringUtils.split(info.getTags(), ','));
            visitorsVo.setFateValue(visitor.getScore().intValue());
            result.add(visitorsVo);
        }

        return ResponseEntity.ok(result);
    }



}
